<?php

namespace app\api\controller\ai;

use thinkct\controller\Frontend;
use app\common\model\ai\app\Models as AppModel;
use app\common\model\ai\app\Category;
use app\common\model\ai\Group;
use thinkct\facade\ChatData;

class App extends Frontend
{
    protected array $noNeedLogin = ['index', 'category'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 获取分类
     */
    public function category()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);

        // 获取列表
        $category = Category::where('status', 1)->paginate($limit, false, [
            'page' => $page
        ]);

        $this->success('获取成功', $category);
    }

    /**
     * 获取应用
     */
    public function index()
    {
        $category_id = $this->request->get('category_id', '');
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);

        // 获取应用
        $app = AppModel::where('status', 1);

        if ($category_id) {
            $app = $app->where('category_id', $category_id);
        }

        $app = $app->paginate($limit, false, [
            'page' => $page
        ]);

        // 遍历数据
        foreach ($app as &$item) {
            $item['tags'] = Category::where('id', $item['category_id'])->value('name');
            $item['is_download'] = 0;
            // 判断是否已经安装
            $group = Group::where(['user_id'=>$this->auth->id, 'app_id'=>$item['id']])->find();
            if($group) {
                $item['is_download'] = 1;
            }
        }

        $this->success('获取成功', $app);
    }

    /**
     * 安装应用
     */
    public function install()
    {
        $id = $this->request->post('id', '');
        $type = $this->request->post('type', '');

        // 获取应用信息
        $app = AppModel::where(['id'=>$id,'status'=>1])->find();
        if(!$app) {
            $this->error('应用不存在');
        }

        // 卸载应用
        if($type === 'uninstall') {
            Group::where(['user_id'=>$this->auth->id, 'app_id'=>$app['id']])->delete();
            $this->success('卸载成功');
        }

        // 创建聊天组
        $group = ChatData::createGroup($app->name, $this->auth->id, $id);
        $this->success('111', $group);

        // 增加下载次数
        $app->download = $app->download + 1;
        $app->save();

        $this->success('安装成功', [
            'group_id' => $group->id
        ]);
    }

















}